<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '修改' : '新增'"
    width="1000"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="85"
      size="default"
      label-position="top"
    >
      <div class="high-form-title">策略信息</div>

      <el-row :gutter="21">
        <el-col :span="16">
          <el-form-item label="策略名称">
            <el-input
              v-model="form.conf_name"
              placeholder="请输入策略名称"
              maxlength="10"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="策略状态">
            <el-switch
              v-model="form.enable_status"
              :active-value="0"
              :inactive-value="1"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="策略状态类型" prop="status_type">
            <el-select
              v-model="form.status_type"
              placeholder="请选择"
              class="w-full"
              @change="changeStatusType"
            >
              <el-option
                v-for="item in options['goods.GoodsStatusConfig']?.[0].statusTypeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行频率" prop="exec_frequency">
            <el-select v-model="form.exec_frequency" placeholder="请选择" class="w-full">
              <el-option
                v-for="item in options['goods.GoodsStatusConfig']?.[0].execFrequencyText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="策略备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入备注"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="high-form-title">处理范围</div>
      <el-row :gutter="21">
        <el-col :span="14">
          <el-form-item label="产品分类">
            <select-category
              class="w-full"
              v-model="form.spu_category"
              :showAllLevels="false"
              :defaultProps="defaultProps"
            ></select-category>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排除销售状态">
            <el-select
              v-model="form.ignore_sale_status"
              placeholder="请选择"
              class="w-full"
              multiple
              collapse-tags
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排除开发状态">
            <el-select
              v-model="form.ignore_dev_status"
              placeholder="请选择"
              class="w-full"
              multiple
              collapse-tags
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].devStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="排除SKU">
            <template #label>
              排除SKU
              <span class="text-[#FF0000]">(排除SKU，若有多个SKU，使用；分隔)</span>
            </template>

            <el-input
              v-model="form.ignore_sku_handle"
              placeholder="排除SKU"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="high-form-title">状态策略规则</div>
      <el-table
        :data="form.config"
        height="300"
        style="width: 100%"
        border
        ref="multipleTableRef"
        v-if="form.status_type == 1"
      >
        <el-table-column prop="liveness" label="状态项" width="200">
          <template #default="{ row }">
            {{ row.liveness == 1 ? "新品" : row.liveness == 2 ? "老品" : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="判断逻辑">
          <template #default="{ row }">
            <template v-if="row.liveness == 1">
              <div class="flex items-center">
                <el-select class="mr-2 w-30" v-model="row.condition.field">
                  <el-option
                    v-for="(item, index) in timeOptions"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                在最近
                <el-input
                  v-model="row.condition.start"
                  style="width: 100px"
                  class="ml-1 mr-1"
                  placeholder="天数"
                />
                至<el-input
                  v-model="row.condition.end"
                  style="width: 100px"
                  placeholder="天数"
                  class="ml-1 mr-1"
                />
                范围内
              </div>
            </template>
            <template v-if="row.liveness == 2">
              <div class="flex items-center">
                <el-select class="mr-2 w-30" v-model="row.condition.field">
                  <el-option
                    v-for="(item, index) in timeOptions"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-select class="mr-2 w-30" v-model="row.condition.operate">
                  <el-option
                    v-for="(item, index) in notationOptions"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-input
                  v-model="row.condition.start"
                  class="w-40"
                  placeholder="请输入天数"
                />
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        :data="form.config"
        style="width: 100%"
        border
        ref="multipleTableRef"
        v-if="form.status_type == 2"
      >
        <el-table-column prop="product_level" label="状态项" width="100">
          <template #default="{ row }">
            {{ computedLevelName(row.product_level) }}
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="判断逻辑">
          <template #default="{ row }">
            <template v-if="row.product_level == 1">
              <div
                class="flex items-center ml-8"
                v-for="(item, index) in row.condition"
                :key="index"
              >
                <div class="flex items-center text-xs">
                  90天月均销量 {{ item[0].operate }}
                  <el-input
                    size="small"
                    class="ml-2"
                    v-model="item[0].start"
                    style="width: 100px"
                  >
                    <template #append>个</template></el-input
                  >
                </div>
                <div class="px-2 font-bold">且</div>
                <div class="flex items-center text-xs">
                  90天月均销售毛利率 {{ item[1].operate }}
                  <el-input
                    size="small"
                    class="ml-2"
                    v-model="item[1].start"
                    style="width: 100px"
                  >
                    <template #append>%</template></el-input
                  >
                </div>
              </div>
            </template>
            <template v-if="row.product_level == 2">
              <div
                class="flex items-center pl-8 relative"
                v-for="(item, index) in row.condition"
                :key="index"
              >
                <template v-if="index == 0">
                  <div class="flex items-center text-xs">
                    90天月均销量 {{ item[0].operate }}
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[0].start"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                  </div>
                  <div class="px-2 font-bold">且</div>
                  <div class="flex items-center text-xs">
                    90天月均销售毛利率 {{ item[1].operate }}
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[1].start"
                      style="width: 100px"
                    >
                      <template #append>%</template></el-input
                    >
                  </div>
                </template>
                <template v-if="index == 1">
                  <div class="absolute left-0 -top-2 font-bold text-[#FF0000]">或</div>
                  <div class="flex items-center text-xs mt-2">
                    <el-input
                      size="small"
                      class="mr-2"
                      v-model="item[0].start"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                    > 90天月均销量 >=
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[1].start"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                  </div>
                </template>
              </div>
            </template>
            <template v-if="row.product_level == 3">
              <div
                class="flex items-center pl-8 relative"
                v-for="(item, index) in row.condition"
                :key="index"
              >
                <div class="flex items-center text-xs">
                  <el-input
                    size="small"
                    class="mr-2"
                    v-model="item[0].start"
                    style="width: 100px"
                  >
                    <template #append>个</template></el-input
                  >
                  > 90天月均销量 >=
                  <el-input class="ml-2" v-model="item[0].end" style="width: 100px">
                    <template #append>个</template></el-input
                  >
                </div>
                <div class="px-2 font-bold">且</div>
                <div class="flex items-center text-xs">
                  90天月均销售毛利率 >=
                  <el-input
                    size="small"
                    class="ml-2"
                    v-model="item[1].start"
                    style="width: 100px"
                  >
                    <template #append>%</template></el-input
                  >
                </div>
              </div>
            </template>
            <template v-if="row.product_level == 4">
              <div class="" v-for="(item, index) in row.condition" :key="index">
                <div class="flex pl-8" v-if="index == 0">
                  <div class="flex items-center text-xs">
                    <el-input
                      size="small"
                      class="mr-2"
                      v-model="item[0].start"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                    > 90天月均销量 >=
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[0].end"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                  </div>
                  <div class="px-2 font-bold">且</div>
                  <div class="flex items-center text-xs">
                    90天月均销售毛利率 {{ item[1].operate }}
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[1].start"
                      style="width: 100px"
                    >
                      <template #append>%</template></el-input
                    >
                  </div>
                </div>
                <div class="flex relative pl-8" v-if="index == 1">
                  <div class="absolute left-0 -top-2 font-bold text-[#FF0000]">或</div>
                  <div class="flex items-center text-xs mt-2">
                    <el-input
                      size="small"
                      class="mr-2"
                      v-model="item[0].start"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                    > 90天月均销量 >=
                    <el-input
                      size="small"
                      class="ml-2"
                      v-model="item[0].end"
                      style="width: 100px"
                    >
                      <template #append>个</template></el-input
                    >
                  </div>
                </div>
                <div class="flex relative pl-8" v-if="index == 2">
                  <div class="absolute left-0 -top-2 font-bold text-[#FF0000]">或</div>
                  <div class="flex items-center text-xs mt-2">
                    90天月均销量 = 0,
                    <el-select
                      v-model="item[0].field"
                      placeholder="请选择"
                      style="width: 100px"
                      size="small"
                    >
                      <el-option
                        v-for="item in leavlTimeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <el-select
                      v-model="item[0].operate"
                      placeholder="请选择"
                      style="width: 100px"
                      size="small"
                    >
                      <el-option
                        v-for="item in notationOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <el-input
                      class="ml-2"
                      size="small"
                      v-model="item[0].start"
                      placeholder="请输入天数"
                      style="width: 100px"
                    />
                  </div>
                </div>
              </div>
            </template>
            <template v-if="row.product_level == 5">
              <div v-for="(item, index) in row.condition" :key="index">
                <div class="flex items-center text-xs">
                  90天月均销量 = 0,
                  <el-select
                    v-model="item[0].field"
                    placeholder="请选择"
                    style="width: 100px"
                    size="small"
                  >
                    <el-option
                      v-for="item in leavlTimeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-select
                    v-model="item[0].operate"
                    placeholder="请选择"
                    style="width: 100px"
                    size="small"
                  >
                    <el-option
                      v-for="item in notationOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-input
                    class="ml-2"
                    v-model="item[0].start"
                    placeholder="请输入天数"
                    style="width: 100px"
                    size="small"
                  />
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="condition_exec_type" label="满足条件执行" width="160">
          <template #default="{ row }">
            <el-select
              v-model="row.condition_exec_type"
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in options['goods.GoodsStatusConfig']?.[0].conditonExecText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="py-2">
      <p class="text-[#999]">注:</p>
      <p class="text-[#999]">
        1、策略根据指定时间自动执行，新增或编辑后若需要马上生效，可手动点击‘手动执行’；
      </p>
      <p class="text-[#999]">
        2、产品分类支持多选，但同一个状态类型策略中，启用状态下的策略不支持重复配置；
      </p>
      <p class="text-[#999]">3、执行数据默认排除产品类型=辅料；</p>
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { createGoodsStatusConfig, editGoodsStatusConfig } from "../api";
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectCategory from "@/components/SelectCategory";
import { notationOptions, timeOptions, leavlTimeOptions } from "../data.js";
import { deepClone } from "@/utils/index.js";
const emits = defineEmits(["query"]);
const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
});

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  multiple: true,
};

const { options } = toRefs(props);

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    tag_name: [{ required: true, message: "请输入标签名称", trigger: "change" }],
    status_type: [{ required: true, message: "请选择标签类型", trigger: "blur" }],
    exec_frequency: [{ required: true, message: "请选择执行频率", trigger: "blur" }],
    tag_color: [{ required: true, message: "请选择标签颜色", trigger: "blur" }],
  },
  shopOptions: [],
  handleType: "",
  load: false,
});

const { rules, form, visible, loading, formRef, shopOptions, handleType, load } = toRefs(
  data
);
const open = async (type, row) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  handleType.value = type;
  if (type == "edit") {
    form.value = deepClone(row);
    form.value.ignore_sku_handle = row.ignore_sku ? row.ignore_sku.join(";") : "";
  }
  visible.value = true;
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = Object.assign({}, form.value);
      if (formData.spu_category?.length) {
        formData.last_spu_category = formData.spu_category.map(
          (subArray) => subArray[subArray.length - 1]
        );
      } else {
        formData.last_spu_category = [];
      }

      formData.ignore_sku = form.value.ignore_sku_handle.replace(/\s+/g, "").split(";");

      loading.value = true;
      if (formData.id) {
        editGoodsStatusConfig(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createGoodsStatusConfig(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const initForm = () => {
  form.value = getForm();
  shopOptions.value = [];
};

// 初始化
const getForm = () => {
  return {
    remark: "",
    enable_status: 0,
    config: [
      {
        liveness: 1,
        condition: {
          end: "",
          field: "dev_add_time",
          start: "",
          operate: "between",
        },
      },
      {
        liveness: 2,
        condition: {
          end: "",
          field: "dev_add_time",
          start: "",
          operate: ">",
        },
      },
    ],
  };
};

const getConfig1 = () => {
  return [
    {
      liveness: 1,
      condition: {
        end: "",
        field: "dev_add_time",
        start: "",
        operate: "between",
      },
    },
    {
      liveness: 2,
      condition: {
        end: "",
        field: "dev_add_time",
      },
    },
  ];
};

const getConfig2 = () => {
  return [
    {
      condition: [
        [
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: ">=",
          },
          {
            field: "ninety_average_sales_percent",
            start: "",
            operate: ">=",
          },
        ],
      ],
      product_level: 1,
      condition_relation: "or",
      condition_exec_type: "",
    },
    {
      condition: [
        [
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: ">=",
          },
          {
            field: "ninety_average_sales_percent",
            start: "",
            operate: "<",
          },
        ],
        [
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: ">=",
          },
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: "<",
          },
        ],
      ],
      product_level: 2,
      condition_relation: "or",
      condition_exec_type: "",
    },
    {
      condition: [
        [
          {
            end: "",
            field: "ninety_average_month_sales",
            start: "",
            operate: "between",
          },
          {
            field: "ninety_average_sales_percent",
            start: "",
            operate: ">=",
          },
        ],
      ],
      product_level: 3,
      condition_relation: "or",
      condition_exec_type: "",
    },
    {
      condition: [
        [
          {
            end: "",
            field: "ninety_average_month_sales",
            start: "",
            operate: "between",
          },
          {
            field: "ninety_average_sales_percent",
            start: "",
            operate: "<",
          },
        ],
        [
          {
            end: "",
            field: "ninety_average_month_sales",
            start: "",
            operate: "between",
          },
        ],
        [
          {
            field: "create_time",
            start: "",
            operate: "<",
          },
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: "=",
          },
        ],
      ],
      product_level: 4,
      condition_relation: "or",
      condition_exec_type: "",
    },
    {
      condition: [
        [
          {
            field: "create_time",
            start: "",
            operate: ">=",
          },
          {
            field: "ninety_average_month_sales",
            start: "",
            operate: "=",
          },
        ],
      ],
      product_level: 5,
      condition_relation: "or",
      condition_exec_type: "",
    },
  ];
};

onMounted(() => {
  initForm();
});

const close = () => {
  initForm();
  visible.value = false;
};

const computedLevelName = (value) => {
  const find = options.value["goods.GoodsSku"]?.[0].productLevelText.find(
    (i) => i.value == value
  );

  return find?.label;
};

const changeStatusType = async (val) => {
  if (!form.value.current_status_type) {
    form.value.current_status_type = val;
    if (val == 1) {
      form.value.config = getConfig1();
    } else if (val == 2) {
      form.value.config = getConfig2();
    }
  } else {
    const is_flag = await handleConfirm(
      "是否更换策略状态类型，点击确认将清空状态策略规则?"
    );
    if (is_flag) {
      if (val == 1) {
        form.value.config = getConfig1();
      } else if (val == 2) {
        form.value.config = getConfig2();
      }
    } else {
      form.value.status_type = form.value.current_status_type;
    }
  }
};

// promise 封装二次确认
const handleConfirm = async (title) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(title, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

defineExpose({ open });
</script>
<style lang="scss">
.label-color {
  .el-radio__input {
    display: none !important;
  }
}

.m-0 {
  margin: 0 !important;
}
</style>
